import styles from "@/assets/scss/details.module.scss";
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import DOMPurify from "dompurify";
import { Empty } from "antd";

function DetailsPages() {
    const [Data, setData] = useState(null);
    const loading = $.loading();
    const [id, setId] = useState(null);
    const navigate = useNavigate();
    const [previous, setPrevious] = useState(null);
    const [next, setNext] = useState(null);
    const type = getSearchString("type") || null;
    const [initialized, setInitialized] = useState(false);
    const contentRef = useRef(null);
    
    const handleImageClick = (e) => {
        const target = e.target;
        if (target instanceof HTMLImageElement) {
            const imgs = contentRef.current.querySelectorAll("img");
            const urls = Array.from(imgs).map(img => img.src);
            const index = Array.from(imgs).findIndex(img => img === target);
            debugger;
            imageViewer(urls, {
                currIndex: index,
                loop: true,
                showPage: true,
                max: 3
            });
        }
    };

    const loadData = async () => {
        if(!id || !initialized) return;
        loading.show();
        setData(null);
        setPrevious(null);
        setNext(null);
        try {
            const response = await axios.get(`${$.baseUrl}/api/article/detail/${id}`,{
                params: {
                    validTypes: type
                }
            });
            if(!response.data.success) {
                alert(response.data.message, null, "warning");
                return;
            };
            if(response.data.data.previous) {
                setPrevious(response.data.data.previous);
            };
            if(response.data.data.next) {
                setNext(response.data.data.next);
            };
            let processedHtml = response.data.data.current.ARTICLE_CONTENT.replace(/<img[^>]*src="([^"]*)"[^>]*>/g, function(match, p1) {
                var fileName = p1.split('/').pop();
                return match.replace(`src="${p1}"`, `src="${$.baseUrl}/public/imgs/other/${fileName}"`);
            });
            response.data.data.current.ARTICLE_CONTENT = processedHtml;
            setData(response.data.data.current);
        } catch (error) {
            alert(error.message, null, "error");
        } finally {
            loading.hide();
        }
    };

    useEffect(() => {
        if (!contentRef.current || !Data) return;
        contentRef.current.addEventListener('click', handleImageClick);
        return () => {
            contentRef.current?.removeEventListener('click', handleImageClick);
        };
    }, [Data]);

    useEffect(() => {
        // 只有访问详情页时才检查ID
        if (window.location.pathname.includes("/details")) {
            const currentId = getSearchString("ID");
            if (!currentId) {
                navigate("/404");
                return;
            }
            setId(currentId);
        }
        setInitialized(true);
    }, [location.search, navigate]);

    useEffect(() => {
        if(initialized) {
            loadData();
        };
    },[id, initialized]);

    return (
        <div className={`m-t-20 p-b-48 ${styles.main}`}>
            {Data ? (
                <>
                    <div className={`font-48 text-center ${styles.title}`}>{Data.ARTICLE_BROCHURE}</div>
                    <div className={`rowCenterCenter m-t-32 font-16 ${styles.info}`}>
                        <div className="lineHeight-48">作者：{Data.ARTICLE_AUTHOR}</div>
                        <div className="m-l-48">时间：{Data.CREATED_AT}</div>
                    </div>
                    <div ref={contentRef} className={`${styles.mainBox} font-16 p-b-48`} dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(Data.ARTICLE_CONTENT)}}></div>
                    <div className={`rowBetweenCenter font-20 p-t-68`}>
                        <div>
                            {previous ? (
                                <Link to={`/details?ID=${previous.ARTICLE_ID}${type ? "&type=" + type : ''}`} className={`rowStartCenter ${styles.articleSet}`}>
                                    <div>上一篇：</div>
                                    <div>{previous.ARTICLE_BROCHURE}</div>
                                </Link>
                            ) : null}
                        </div>
                        <div>
                            {next ? (
                                <Link to={`/details?ID=${next.ARTICLE_ID}${type ? "&type=" + type : ''}`} className={`rowStartCenter ${styles.articleSet}`}>
                                    <div>下一篇：</div>
                                    <div>{next.ARTICLE_BROCHURE}</div>
                                </Link>
                            ) : null}
                        </div>
                    </div>
                </>
            ) : (
                <div className={`${styles.empty} rowCenterCenter`}>
                    <Empty />
                </div>
            )}
        </div>
    )
};

export default DetailsPages;